﻿using Furion;
using Furion.FriendlyException;
using Gear.Core.ErrorControl;
using Gear.Web.Api.DynamicDataApi.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Gear.Web.Api.DynamicDataApi.Macro
{
    /// <summary>
    /// 查询语句正则宏
    /// </summary>
    public static class RegexMacro
    {
        public readonly static int type=Convert.ToInt32(App.Configuration["SqlFilter:Level"]);

        #region == 验证规则 ==
        public static System.Text.RegularExpressions.Regex[] reqRegex = new System.Text.RegularExpressions.Regex[]
        {
            new System.Text.RegularExpressions.Regex(@"req\s*\(\s*""([^""]+)\s*""\)",RegexOptions.IgnoreCase),
            new System.Text.RegularExpressions.Regex(@"req\s*\(\s*'([^']+)\s*'\)",   RegexOptions.IgnoreCase)
        };
        //不校验关键属性
        //public static Regex[] reqlowRegex = new Regex[]
        //{
        //    new Regex(@"reqlow\s*\(\s*""([^""]+)\s*""\)",RegexOptions.IgnoreCase),
        //    new Regex(@"reqlow\s*\(\s*'([^']+)\s*'\)",   RegexOptions.IgnoreCase)
        //};
        #endregion

        /// <summary>
        /// 正则匹配
        /// </summary>
        /// <param name="_content"></param>
        /// <param name="param"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string RegexTrans(string _content, Dictionary<string, object> param)
        {
            if (string.IsNullOrEmpty(_content)) throw Oops.Oh(ErrorCodeModel.E2100_2, "");
            if (param!=null)
            {
                string func(string name)
                {
                    param.TryGetValue(name, out object res);

                    switch ((RegexType)type)
                    {
                        case RegexType.Nomal:
                            if (res != null) SqlFilter_Nomal(res.ToString());
                            break;
                        case RegexType.Low:
                            if (res != null) SqlFilter_Low(res.ToString());
                            break;
                        default:
                            if (res != null) SqlFilter_Nomal(res.ToString());
                            break;
                    }
                    return res?.ToString();
                }

                foreach (KeyValuePair<string, object> kvp in param)
                {
                    
                    
                    foreach (var reg in reqRegex)
                    {
                        var match = reg.Match(_content);
                        while (match.Success)
                        {
                            var varVal = func(match.Groups[1].Value) ?? match.Groups[1].Value;
                            
                            _content = _content.Replace(match.Value, varVal);
                            match = reg.Match(_content);
                        }
                    }
                }

            }
            return _content;
        }


        #region == Sql注入过滤规则 ==
        // 标准规则
        private static void SqlFilter_Nomal(string value)
        {
            if (!string.IsNullOrEmpty(value) && value != null)
            {
                string word = "and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join|create|in|not";

                foreach (string i in word.Split('|'))
                {
                    if ((value.IndexOf(i + " ") > -1) || (value.ToLower().IndexOf(" " + i) > -1))
                    {
                        throw Oops.Oh(ErrorCodeModel.E1200_1, i);
                    }
                }
            }
        }
        // 降级规则
        private static void SqlFilter_Low(string value)
        {
            if (!string.IsNullOrEmpty(value) && value != null)
            {

                string word = "exec|insert|delete|update|chr|mid|master|truncate|char|declare|create";

                foreach (string i in word.Split('|'))
                {
                    if ((value.IndexOf(i + " ") > -1) || (value.ToLower().IndexOf(" " + i) > -1))
                    {
                        throw Oops.Oh(ErrorCodeModel.E1200_1, i);
                    }
                }
            }
        }
        #endregion
    }

    
}
